<?php
/**
 * Knihovna_Controller_Plugin_Auth
 *
 * @author Petr Laslo
 * @license MIT License
 * @package Knihovna\Controller\Plugin
 * @link https://code.google.com/p/knihovna/
 */
class Knihovna_Controller_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
    /** @var Zend_Acl **/
    protected $acl;

    /** @var string **/
    protected $_roleName;

    /** @var array **/
    protected $_errorPage;

    /*
     * @param string $roleName
     * @return void
     */
    public function __construct($roleName = 'guest')
    {
        $this->_errorPage = array('module' => 'default',
        'controller' => 'error',
        'action' => 'denied');

        $this->setRole($roleName);

        $this->acl = Zend_Registry::get('acl');
    }

    /*
     * setRole
     * @param string $roleName
     * @return void
     */
    public function setRole($roleName)
    {
        $this->_roleName = $roleName;
    }

    /*
     * getRole
     * @param void
     * @return string $roleName
     */
    public function getRole()
    {
        return $this->_roleName;
    }

    /**
     * @param  Zend_Controller_Request_Abstract $request
     * @return void
     */
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $role = Zend_Auth::getInstance()->hasIdentity() ? Zend_Auth::getInstance()->getIdentity()->role : 'guest';
        $this->setRole($role);
        $view = Zend_Layout::getMvcInstance()->getView();
        $view->navigation()->setAcl($this->acl)->setRole($role);

        $resourceName = '';
        if ($request->getModuleName() != 'default') {
            $resourceName .= $request->getModuleName() . ':';
        }
        $resourceName .= $request->getControllerName();

        if (!$this->acl->isAllowed(
            $this->getRole(), $resourceName, $request->getActionName()
        )) {
            if ($this->getRole() == 'guest') {
                $request->setModuleName('default');
                $request->setControllerName('user');
                $request->setActionName('login');
            }else {
                $request->setModuleName('default');
                $request->setControllerName('index');
                $request->setActionName('index');
            }
        }
    }

}
